package com.xuecheng.auth.controller;

import com.xuecheng.api.auth.AuthControllerApi;
import com.xuecheng.auth.service.AuthService;
import com.xuecheng.framework.domain.ucenter.ext.AuthToken;
import com.xuecheng.framework.domain.ucenter.request.LoginRequest;
import com.xuecheng.framework.domain.ucenter.response.JwtResult;
import com.xuecheng.framework.domain.ucenter.response.LoginResult;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.utils.CookieUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author ShengJinFeng
 * @version V1.0
 * @ClassName AuthController
 * @Description (用户认证)
 * @date 2020/3/10 20:25
 * @since V1.0
 */
@RestController
@Api(value = "用户认证",description = "用户认证接口")
public class AuthController implements AuthControllerApi {

    @Autowired
    private AuthService authService;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @Override
    @ApiOperation("登录")
    @PostMapping("/userlogin")
    public LoginResult login(LoginRequest loginRequest) {
        //登录认证获取令牌
        AuthToken authToken = authService.loginAuth(loginRequest);
        //将令牌写入cookie
        String access_token = authToken.getAccess_token();
        savedCookie(access_token);
        return new LoginResult(CommonCode.SUCCESS,access_token);
    }

    @Override
    @ApiOperation("退出")
    @PostMapping("/userlogout")
    public ResponseResult logout() {
        //获取cookie中的token
        String accessToken = getTokenFormCookie();
        //删除redis中得token
        authService.deleteRedis(accessToken);
        //删除cookie中得token
        clearCookie(accessToken);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    @ApiOperation("查询userjwt令牌")
    @GetMapping("/userjwt")
    public JwtResult userjwt() {
        //获取cookie中的token
        String accessToken = getTokenFormCookie();
        if (accessToken == null){
            return new JwtResult(CommonCode.FAIL,null);
        }
        AuthToken authToken = authService.findJwtByToken(accessToken);
        if (authToken == null){
            return new JwtResult(CommonCode.FAIL,null);
        }
        return new JwtResult(CommonCode.SUCCESS,authToken.getJwt_token());
    }

    /**
     * @Description 获取cookie中的token
     * @author ShengJinFeng
     * @date 2020/3/11
     */
    private String getTokenFormCookie() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String> cookieMap = CookieUtil.readCookie(request, "uid");
        if (cookieMap != null && cookieMap.get("uid") != null){
            return cookieMap.get("uid");
        }
        return null;
    }

    /**
     * @Description 将令牌写入cookie
     * @author ShengJinFeng
     * @date 2020/3/11
     */
    private void savedCookie(String access_token) {
        //获取响应
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //访问路径
        String path = "/";
        //coolie名称
        String name = "uid";
        String value = access_token;
        //httpOnly设置为true时浏览器获取不了，设置为false时浏览器可以获取到
        CookieUtil.addCookie(response,cookieDomain,path,name,value,cookieMaxAge,false);
    }

    /**
     * @Description 将令牌从cookie中清除,将有效期改为0就可以了
     * @author ShengJinFeng
     * @date 2020/3/11
     */
    private void clearCookie(String access_token) {
        //获取响应
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        //HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //访问路径
        String path = "/";
        //coolie名称
        String name = "uid";
        String value = access_token;
        //httpOnly设置为true时浏览器获取不了，设置为false时浏览器可以获取到
        CookieUtil.addCookie(response,cookieDomain,path,name,value,0,false);
    }
}
